/*
 * Copyright (C) 2009 M. Hautle.
 * 
 * This file is part of TrackedBean.
 * 
 * TrackedBean is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
 * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 * 
 * TrackedBean is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along with TrackedBean. If not, see
 * <http://www.gnu.org/licenses/>.
 */
package bmodeling;

import java.io.*;
import java.net.*;

/**
 * Classloader for BModeling.
 * 
 * @author M. Hautle
 * @since 13.09.08
 */
public class Loader extends URLClassLoader {
	/** The Openoffice lib names. */
	public static final String[] OOO_LIBS = { "unoil.jar", "juh.jar", "jurt.jar", "ridl.jar" };

	/**
	 * Default constructor
	 * 
	 * @param libPath The library path
	 * @param oooPath The openoffice library path
	 * @throws MalformedURLException
	 */
	public Loader(String libPath, String oooPath) throws MalformedURLException {
		super(getLibs(libPath, oooPath));
	}

	/**
	 * @param libPath The library path
	 * @param oooPath The openoffice path
	 * @return A list of urls for the libraries in the specified folders
	 * @throws MalformedURLException
	 */
	private static URL[] getLibs(String libPath, String oooPath) throws MalformedURLException {
		final File[] libs = new File(libPath).listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.endsWith(".jar");
			}
		});
		final URL[] res = new URL[libs.length + OOO_LIBS.length];
		oooPath = getOOOLibDir(oooPath);
		// add the normal libs
		for (int i = 0; i < libs.length; i++)
			res[i] = libs[i].toURI().toURL();
		// add the ooo libs
		for (int i = 0, j = libs.length; i < OOO_LIBS.length; i++, j++)
			res[j] = new File(oooPath + OOO_LIBS[i]).toURI().toURL();
		return res;
	}

	/**
	 * Checks if the given folder contains the {@link #OOO_LIBS}.
	 * 
	 * @param dir The folder to check
	 * @return True if the given folder contains the libs
	 */
	public static boolean checkOOODir(String dir) {
		dir = getOOOLibDir(dir);
		for (String f : OOO_LIBS)
			if (!new File(dir + f).exists())
				return false;
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		return super.findClass(name);
	}

	/**
	 * Returns the openoffice lib dir of an openoffice dir.
	 * 
	 * @param oooDir The openoffice dir
	 * @return The openoffice lib dir
	 */
	private static String getOOOLibDir(String oooDir) {
		return oooDir + File.separator + "program" + File.separator + "classes" + File.separator;
	}
}
